#include <tasks_manager/task_manager_node.h>

/*******************************************
 * 任务管理 ROS服务接口
 *******************************************/

// 任务生成服务
bool TaskManagerNode::TaskGenerateServer(v3_msgs::TaskGenerateManagerRequest &req, v3_msgs::TaskGenerateManagerResponse &res){
    ROS_INFO("TaskGenerateServer option: %d", req.option);
    Status status;
    TaskSingle task_single;
    cout << "req.task_base.path_gen.path_types.size(): " << req.task_base.path_gen.path_types.size() << endl;
    task_single.task_base = __msg_convert.V3Msgs2TaskBase(req.task_base);
    task_single.task_base.edge_mode = EdgeMode::EDGE_ZERO_MODE;
    cout << "task_single.task_base.path_gen.path_types.size(): " << task_single.task_base.path_gen.path_types.size() << endl;
    switch(req.option){ 
        case req.PREVIEW_TASK:           //预览单个任务
            status = TaskGenerateHandle(task_single, false);
            break;
        case req.CREATE_TASK:            //创建单个任务
            // 保存到数据库中
            status = TaskGenerateHandle(task_single, true);
            break;
        default:
            break;
    }
    if(!status.success){
        ROS_ERROR("TaskGenerateServer: %s", status.message.c_str());
    }
    res.task_single = __msg_convert.TaskSingle2V3Msgs(task_single);
    res.response.success = status.success;
    res.response.message = status.message;
    return true;
}

// 单个任务服务
bool TaskManagerNode::TaskSingleServer(v3_msgs::TaskSingleManagerRequest &req, v3_msgs::TaskSingleManagerResponse &res){
    ROS_INFO("TaskSingleServer option: %d", req.option);
    Status status;
    TaskSingle task_single = __msg_convert.V3Msgs2TaskSingle(req.task_single);
    TaskSingle new_task_single = __msg_convert.V3Msgs2TaskSingle(req.new_task_single);
    switch(req.option){    
        case req.DELETE_TASK:           //删除单个任务
            status = TaskSingleDelete(task_single.task_base.task_name, task_single.task_base.map_base.name);
            break;
        case req.DELETE_TASK_WITH_MAP:      //删除指定地图下所有单个任务
            status = TaskSingleDeleteForNapName(task_single.task_base.map_base.name);
            break;
        case req.DELETE_ALL_TASK:           //删除所有地图下单个任务
            status = TaskSingleDeleteAll();
            break;
        case req.UPDATE_TASK:               //更改单个任务, 重命名、修改清洁模式、外设模式、清洁速度
            // status = TaskSingleRename(task_single.task_base.task_name, task_single.task_base.map_base.name, 
            //     new_task_single.task_base.task_name);
            status = TaskSingleUpdate(task_single.task_base.task_name, task_single.task_base.map_base.name, 
                new_task_single.task_base);
            break;
        case req.UPDATE_TASK_PATH:          //更新单个任务路径
            status = TaskSingleUpdatePath(task_single.task_base.task_name, task_single.task_base.map_base.name);
            break;
        case req.UPDATE_TASK_PATH_WITH_MAP:          //更新当前地图下单个任务路径
            status = TaskSingleUpdatePathWithMapName();
            break;
        case req.SET_TOP:         //设置置顶 
            status = TaskSingleSetTop(task_single.task_base.task_name, task_single.task_base.map_base.name, task_single.task_base.is_top);
            break;
        case req.UPDATE_MAP_NAME:         //更新地图名称 
            status = TaskSingleUpdateMapName(task_single.task_base.map_base.name, new_task_single.task_base.map_base.name);
            break;    
        case req.QUERY_TASK_INFO:           //查询单个任务信息
            {
                TaskSingle task_single_query;
                status = TaskSingleQuery(task_single.task_base.task_name, task_single.task_base.map_base.name, task_single_query);
                res.task_list.emplace_back(__msg_convert.TaskSingle2V3Msgs(task_single_query));
            }
            break;
        case req.QUERY_TASK_INFO_WITH_MAP:           //查询当前地图下所有单个任务信息
            {
                vector<TaskSingle> task_singles;
                status = TaskSingleListForMapName(task_single.task_base.map_base.name, task_singles);
                for(auto &task_single : task_singles){
                    res.task_list.emplace_back(__msg_convert.TaskSingle2V3Msgs(task_single));
                }
            }
            break;
        case req.QUERY_ALL_TASK_INFO:                //查询所有地图下所有单个任务信息
            {
                vector<TaskSingle> task_singles;
                status = TaskSingleListForAllMap(task_singles);
                for(auto &task_single : task_singles){
                    res.task_list.emplace_back(__msg_convert.TaskSingle2V3Msgs(task_single));
                }
            }            
            break;
        default:
            ;
    }
    res.response.success = status.success;
    res.response.message = status.message;
    return true;

}

// 组合任务服务
bool TaskManagerNode::TaskGroupServer(v3_msgs::TaskGroupManagerRequest &req, v3_msgs::TaskGroupManagerResponse &res){
    ROS_INFO("TaskGroupServer option: %d", req.option);
    Status status;
    TaskGroup task_group = __msg_convert.V3Msgs2TaskGroup(req.task_group);
    TaskGroup new_task_group = __msg_convert.V3Msgs2TaskGroup(req.new_task_group);
    switch(req.option){    
        case req.CREATE_TASK_GROUP:         //创建组合任务 
            status = TaskGroupAdd(task_group);
            break;
        case req.DELETE_TASK_GROUP:         //删除组合任务 
            status = TaskGroupDelete(task_group.group_name);
            break;
        case req.DELETE_ALL_TASK_GROUP:         //删除所有组合任务 
            status = TaskGroupDeleteAll();
            break;
        case req.RENAME_TASK_GROUP:         //重命名组合任务 
            status = TaskGroupRename(task_group.group_name, new_task_group.group_name);
            break;
        case req.SET_TOP:         //设置置顶 
            status = TaskGroupSetTop(task_group.group_name, task_group.is_top);
            break;
        case req.QUERY_TASK_GROUP_INFO:             //查询组合任务信息 
            {
                TaskGroup task_group_query;
                status = TaskGroupQuery(task_group.group_name, task_group_query);
                res.taskgroup_list.emplace_back(__msg_convert.TaskGroup2V3Msgs(task_group_query));
            }
            break;
        case req.QUERY_ALL_GROUP_TASK_INFO:         //查询所有组合任务信息 
            {
                vector<TaskGroup> task_groups;
                status = TaskGroupList(task_groups);
                for(auto &task_group : task_groups){
                    res.taskgroup_list.emplace_back(__msg_convert.TaskGroup2V3Msgs(task_group));
                }
            }
            break;
        default:
            ;
    }
    res.response.success = status.success;
    res.response.message = status.message;
    return true;
}

// 定时任务服务
bool TaskManagerNode::TimerTaskServer(v3_msgs::TimerTaskManagerRequest &req, v3_msgs::TimerTaskManagerResponse &res){
ROS_INFO("TimerTaskServer option: %d", req.option);
    Status status;
    TimerTask timertask = __msg_convert.V3Msgs2TimerTask(req.timertask);
    TimerTask new_timertask = __msg_convert.V3Msgs2TimerTask(req.new_timertask);
    switch(req.option){    
        case req.CREATE_TIMER_TASK:         //创建定时任务 
            status = TimerTaskAdd(timertask);
            break;
        case req.DELETE_TIMER_TASK:         //删除定时任务 
            status = TimerTaskDelete(timertask.timertask_name);
            break;
        case req.DELETE_ALL_TIMER_TASK:     //删除所有定时任务 
            status = TimerTaskDeleteAll();
            break;
        case req.UPDATE_TIMER_TASK:         //更新定时任务 
            status = TimerTaskUpdate(timertask, new_timertask);
            break;
        case req.SET_TOP:         //设置置顶 
            status = TimerTaskSetTop(timertask.timertask_name, timertask.is_top);
            break;
        case req.QUERY_TIMER_TASK_INFO:             //查询定时任务信息 
            {
                TimerTask timertask_query;
                status = TimerTaskQuery(timertask.timertask_name, timertask_query);
                res.timertask_list.emplace_back(__msg_convert.TimerTask2V3Msgs(timertask_query));
            }
            break;
        case req.QUERY_ALL_TIMER_TASK_INFO:         //查询所有定时任务信息 
            {
                vector<TimerTask> timertasks;
                status = TimerTaskList(timertasks);
                for(auto &timertask : timertasks){
                    res.timertask_list.emplace_back(__msg_convert.TimerTask2V3Msgs(timertask));
                }
            }
            break;
        default:
            ;
    }
    res.response.success = status.success;
    res.response.message = status.message;
    return true;
}


/*******************************************
 * 单个任务管理
 *******************************************/

// 任务生成处理
Status TaskManagerNode::TaskGenerateHandle(TaskSingle& task_single, bool save_task){
    Status status;
    cout << "[TaskGenerateHandle] map_name: " << task_single.task_base.map_base.name.c_str() 
        << ", task_name: " << task_single.task_base.task_name.c_str() 
        << ", task_type: " << __msg_convert.TaskType2Str(task_single.task_base.task_type) 
        << ", control_mode: " << __msg_convert.TaskControlMode2Str(task_single.task_base.control_mode) 
        << ", path_action: " << __msg_convert.PathGenerateAction2Str(task_single.task_base.path_gen.path_action)
        << ", polygon size: " << task_single.task_base.polygon.poses.size() 
        << ", path_types: ";
        for(auto& path_type : task_single.task_base.path_gen.path_types)
            cout << __msg_convert.PathGenerateType2Str(path_type) << ",";
        cout << ", path_types_child: ";
        for(auto& path_type : task_single.task_base.path_gen.path_types_child)
            cout << __msg_convert.PathGenerateType2Str(path_type) << ",";
        cout << endl;


    // 校验请求数据
    if(save_task){
        if(task_single.task_base.path_gen.path_action == PathGenerateAction::UNKNOWN || 
            task_single.task_base.path_gen.path_action == PathGenerateAction::FINISHED_RECORD){
            try{  
                if(task_single.task_base.map_base.name.empty()){
                    task_single.task_base.map_base.name = __map_name;
                }
                if(task_single.task_base.map_base.name.empty())
                    throw(string("map_name is empty"));
                if(task_single.task_base.task_name.empty())
                    throw(string("task_name is empty"));
                // 任务已存在
                if(__task_db_ptr->CheckTaskSingleExist(task_single.task_base.map_base.name, task_single.task_base.task_name))
                throw(string(task_single.task_base.task_name + "已存在。"));
            }catch(string& error){
                status.success = false;
                status.message = error;
                return status;
            }
        }
    }
    
    // 生成任务路径
    switch(task_single.task_base.task_type){
        case TaskType::SWEEP_TASK:
            if(__path_gen_use_cln_msgs){    //cln_msgs
                status = __path_gen_interface.GenPolygonTaskWithClnMsg(task_single);
            }
            else{
                status = __path_gen_interface.GenPolygonTaskWithV3Msg(task_single, !save_task);
            }
            break;
        case TaskType::TEACH_TASK:
            if(!task_single.task_base.path_gen.path_types.empty()){
                PathGenerateType path_types_front = task_single.task_base.path_gen.path_types.front();
                if(path_types_front == PathGenerateType::MANUAL_METHOD){
                    if(__path_gen_use_cln_msgs){    //cln_msgs
                        // 保存时，校验地图名称
                        status = __path_gen_interface.GenHandLineWithClnMsg(task_single);
                    }
                    else{
                        status = __path_gen_interface.GenHandPathWithV3Msg(task_single, !save_task);
                    }
                }   
                else if(path_types_front == PathGenerateType::MANUAL_POLYGON_METHOD){
                    // 生成多边形轮廓
                    if(__path_gen_use_cln_msgs){    //cln_msgs
                        status = __path_gen_interface.GenHandPolygonWithClnMsg(task_single, !save_task);
                    }
                    else{
                        status = __path_gen_interface.GenHandPathWithV3Msg(task_single, !save_task);
                        cout << "[0 GenHandPathWithV3Msg] paths size: " << task_single.task_base.paths.size() 
                            << endl;
                        // 解析返回数据
                        if(!task_single.task_base.paths.empty()){
                            cout << "[0 GenHandPathWithV3Msg] front poses size: " << task_single.task_base.paths.front().poses.size();
                            task_single.task_base.polygon.poses = task_single.task_base.paths.front().poses;
                            cout << "[0 GenHandPathWithV3Msg] danger_areas size: " << task_single.task_base.path_gen.danger_areas.size() 
                            << ", polygon size: " << task_single.task_base.polygon.poses.size() 
                            << endl;
                        }  
                    }
                    if(task_single.task_base.path_gen.path_action == PathGenerateAction::FINISHED_RECORD){
                        // 基于二级路径类型请求生成路径
                        // task_single.task_base.path_gen.cancel_polygon_inflation = true;
                        cout << "[TaskGenerateHandle] danger_areas size: " << task_single.task_base.path_gen.danger_areas.size() 
                            << ", polygon size: " << task_single.task_base.polygon.poses.size() 
                            << endl;
                        TaskSingle task_single_manual = task_single;
                        // 修复示教区域生成路径包含示教路线轮廓问题
                        task_single_manual.task_base.paths.clear();    
                        task_single_manual.task_base.edge_paths.clear();
                        task_single_manual.task_base.path_gen.path_types = task_single.task_base.path_gen.path_types_child;
                        task_single_manual.task_base.path_gen.danger_areas = task_single.task_base.path_gen.danger_areas;
                        task_single_manual.task_base.task_type = TaskType::SWEEP_TASK;
                        if(__path_gen_use_cln_msgs){    //cln_msgs
                            status = __path_gen_interface.GenPolygonTaskWithClnMsg(task_single_manual);
                        }
                        else{
                            status = __path_gen_interface.GenPolygonTaskWithV3Msg(task_single_manual, !save_task);
                        }
                        // 封装返回的路径信息
                        task_single.task_base.task_area = task_single_manual.task_base.task_area;
                        task_single.task_base.paths = task_single_manual.task_base.paths;
                        task_single.task_base.edge_paths = task_single_manual.task_base.edge_paths;
                    }
                } 
            }
            break;
        default:
            break;
    }

    // 设置任务路径类型
    auto SetTaskPathType = [](vector<TaskPath>& paths, PathGenerateType path_type) {
        for(auto& path : paths){
            path.path_type = path_type;
        }
    };

    if(!task_single.task_base.path_gen.path_types.empty()){
        // 手动路径类型
        PathGenerateType path_types_front = task_single.task_base.path_gen.path_types.front();
        PathGenerateType path_types_child_front = task_single.task_base.path_gen.path_types_child.empty() ? 
            PathGenerateType::UNKNOWN : task_single.task_base.path_gen.path_types_child.front();
        if(path_types_front == PathGenerateType::MANUAL_POLYGON_METHOD){
            SetTaskPathType(task_single.task_base.paths, path_types_child_front);
        }  
        else
            SetTaskPathType(task_single.task_base.paths, path_types_front);
    }
    SetTaskPathType(task_single.task_base.edge_paths, PathGenerateType::EDGE_METHOD);

    // 保存到数据库
    if(save_task){
        if(task_single.task_base.path_gen.path_action == PathGenerateAction::UNKNOWN || 
            task_single.task_base.path_gen.path_action == PathGenerateAction::FINISHED_RECORD){
            try{
                // 校验请求数据
                if(__task_db_ptr->CheckTaskSingleExist(task_single.task_base.map_base.name, task_single.task_base.task_name))
                    throw(string(task_single.task_base.task_name + "已存在。"));
                if(__task_db_ptr->CheckTaskGroupExist(task_single.task_base.task_name)){
                    throw(string("group_name=" + task_single.task_base.task_name + "已存在。"));
                }
                __task_db_ptr->InsertTaskSingle(task_single);
                // 数据兼容 同样保存一份TaskGroup
                task_single.task_base.paths.clear();        //路径不需要重复保存
                task_single.task_base.edge_paths.clear();   //路径不需要重复保存
                TaskGroup task_group;
                task_group.group_name = task_single.task_base.task_name;
                task_group.task_list.emplace_back(task_single);
                __task_db_ptr->InsertTaskGroup(task_group);
            }catch(string& error){
                status.success = false;
                status.message = error;
                return status;
            }
        }
    }
    return status;
}


// 任务删除处理
Status TaskManagerNode::TaskSingleDelete(string task_name, string map_name){
    Status status;
    LogPub("INFO", "删除单个任务, task_name=" + task_name + ", map_name=" + map_name);
    try{
        // 删除任务组中任务列表信息
        TaskGroupUpdateTaskList(map_name, task_name, "", true);
        // 更新定时任务下所有组合任务  兼容操作
        UpdateTimerTaskTaskGroupList(task_name, "", true);

        __task_db_ptr->DeleteTaskSingle(map_name, task_name);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    } 
    return status;
}


// 任务删除处理 删除当前地图下所有单个任务
Status TaskManagerNode::TaskSingleDeleteForNapName(string map_name){
    Status status;
    LogPub("INFO", "删除当前地图下所有任务, map_name=" + map_name);
    try{
        // 删除任务组中任务地图信息
        TaskGroupUpdateMapName(map_name, "", true);
        // 删除定时任务中任务地图信息
        TimerTaskDeleteByMapName(map_name);
        // 删除单个任务
        __task_db_ptr->DeleteTaskSingleByMapName(map_name);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    } 
    return status;
}

// 任务删除处理 删除所有地图下单个任务
Status TaskManagerNode::TaskSingleDeleteAll(){
    Status status;
    LogPub("INFO", "删除所有地图下所有任务");
    try{
        __task_db_ptr->DeleteTaskSingleAll();
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 任务重命名
Status TaskManagerNode::TaskSingleRename(string task_name, string map_name, string new_task_name){
    Status status;
    LogPub("INFO", "任务重命名, task_name=" + task_name + ", map_name=" + map_name + ", new_task_name=" + new_task_name);
    try{
        // 校验请求数据
        if(__task_db_ptr->CheckTaskSingleExist(map_name, new_task_name))
            throw(string(new_task_name + "已存在。"));
        if(!__task_db_ptr->CheckTaskSingleExist(map_name, task_name))
            throw(string(task_name + "不存在。"));
        // 执行重命名操作
        __task_db_ptr->RenameTaskSingle(map_name, task_name, new_task_name);

        // 更新任务组中任务列表信息
        TaskGroupUpdateTaskList(map_name, task_name, new_task_name, false);
        // 更新定时任务下所有组合任务
        UpdateTimerTaskTaskGroupList(task_name, new_task_name, false);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 单个任务更新地图名称处理
Status TaskManagerNode::TaskSingleUpdateMapName(string map_name, string new_map_name){
    Status status;
    LogPub("INFO", "更新任务地图名称, map_name=" + map_name + ", new_map_name=" + new_map_name);
    try{
        // 更新任务组中任务地图信息
        TaskGroupUpdateMapName(map_name, new_map_name, false);
        // 重命名地图，同步定时任务操作
        TimerTaskUpdateMapName(map_name, new_map_name);
        __task_db_ptr->UpdateTaskSingleMapName(map_name, new_map_name);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    } 
    return status;
}

// 更改单个任务, 重命名、修改清洁模式、外设模式、清洁速度
Status TaskManagerNode::TaskSingleUpdate(string task_name, string map_name, TaskBase task_base){
    Status status;
    LogPub("INFO", "更新单个任务, task_name=" + task_name + ", map_name=" + map_name + ", new_task_name=" + task_base.task_name);
    try{
        // 校验请求数据
        if(!__task_db_ptr->CheckTaskSingleExist(map_name, task_name))
            throw(string(task_name + "不存在。"));
        if(task_name != task_base.task_name){
            if(__task_db_ptr->CheckTaskSingleExist(map_name, task_base.task_name))
                throw(string(task_base.task_name + "已存在。"));
        }
        // 获取任务信息
        TaskSingle task_single;
        __task_db_ptr->GetTaskSingle(map_name, task_name, task_single);
        task_single.task_base.task_name = task_base.task_name;
        task_single.task_base.task_speed = task_base.task_speed;
        task_single.task_base.utils_mode = task_base.utils_mode;
        // 计算新路径，更新路径
        if(!task_single.task_base.path_gen.path_types.empty()){
            PathGenerateType path_types_front = task_single.task_base.path_gen.path_types.front();
            // 示教路线直接跳过
            if(path_types_front != PathGenerateType::MANUAL_METHOD){
                // 更新路径
                task_single.task_base.control_mode = task_base.control_mode;
                if(task_single.task_base.task_type == TaskType::TEACH_TASK){
                    task_single.task_base.path_gen.path_types_child = task_base.path_gen.path_types;
                }
                else{
                    task_single.task_base.path_gen.path_types = task_base.path_gen.path_types;
                }
                TaskSingle task_single_new = task_single;
                task_single_new.task_base.path_gen.path_types = task_base.path_gen.path_types;
                task_single_new.task_base.task_type = TaskType::SWEEP_TASK;
                task_single_new.task_base.paths.clear();
                task_single_new.task_base.edge_paths.clear();
                if(__path_gen_use_cln_msgs){    //cln_msgs
                    status = __path_gen_interface.GenPolygonTaskWithClnMsg(task_single_new);
                }
                else{
                    status = __path_gen_interface.GenPolygonTaskWithV3Msg(task_single_new, true);
                }
                // 封装返回的路径信息
                task_single.task_base.task_area = task_single_new.task_base.task_area;
                task_single.task_base.paths = task_single_new.task_base.paths;
                task_single.task_base.edge_paths = task_single_new.task_base.edge_paths;
            }
        }

        // 更新数据库内容
        __task_db_ptr->UpdateTaskSingle(map_name, task_name, task_single);
        if(task_name != task_base.task_name){
            // 数据兼容，同步更新组合任务名称
            TaskGroupRename(task_name, task_base.task_name);
            // 更新任务组中任务列表信息
            TaskGroupUpdateTaskList(map_name, task_name, task_base.task_name, false);
        }  
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    } 
    return status;
}


// 任务更新路径
Status TaskManagerNode::TaskSingleUpdatePath(string task_name, string map_name){
    Status status;
    try{
        // 校验请求数据
        if(!__task_db_ptr->CheckTaskSingleExist(map_name, task_name))
            throw(string(task_name + "不存在。"));
        // // 请求更新任务路径,获取最新路径  待补全
        // TaskSingle task_single;
        // __task_db_ptr->GetTaskSingle(map_name, task_name, task_single);
        // // 更新任务路径
        // TaskGenerateHandle(task_single, true);
        // // 保存到数据库
        // __task_db_ptr->UpdateTaskSinglePath(map_name, task_name, task_single);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 更新当前地图下单个任务路径
Status TaskManagerNode::TaskSingleUpdatePathWithMapName(){
    Status status;
    try{
        if(!__map_name.empty()){
            // 获取当前地图任务列表
            vector<TaskSingle> task_singles = __task_db_ptr->GetTaskSingleList(__map_name);
            for(auto task_single : task_singles){
                TaskSingleUpdate(
                    task_single.task_base.task_name,
                    __map_name,
                    task_single.task_base
                );
            }
        }
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 设置置顶属性
Status TaskManagerNode::TaskSingleSetTop(string task_name, string map_name, bool is_top){
    Status status;
    LogPub("INFO", "设置任务置顶属性, task_name=" + task_name
        + ", is_top=" + __msg_convert.Bool2Str(is_top));
    try{
        // 校验请求数据
        if(!__task_db_ptr->CheckTaskSingleExist(map_name, task_name))
            throw(string(task_name + "不存在。"));
        // 设置置顶属性
        __task_db_ptr->UpdateTaskSingleIsTop(map_name, task_name, is_top);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }    
    return status;
}

// 任务信息查询
Status TaskManagerNode::TaskSingleQuery(string task_name, string map_name, TaskSingle& task_single){
    Status status;
    LogPub("INFO", "任务信息查询, task_name=" + task_name + ", map_name=" + map_name);
    try{
        // 校验请求数据
        if(!__task_db_ptr->CheckTaskSingleExist(map_name, task_name))
            throw(string(task_name + "不存在。"));
        // 任务信息查询
        __task_db_ptr->GetTaskSingle(map_name, task_name, task_single);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }    
    return status;
}

// 任务列表查询 指定地图
Status TaskManagerNode::TaskSingleListForMapName(string map_name, vector<TaskSingle>& task_singles){
    Status status;
    // LogPub("INFO", "任务列表查询, map_name=" + map_name);
    try{
        task_singles = __task_db_ptr->GetTaskSingleList(map_name);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }  
    return status;
}

// 所有任务列表查询 不同地图
Status TaskManagerNode::TaskSingleListForAllMap(vector<TaskSingle>& task_singles){
    Status status;
    // LogPub("INFO", "所有地图下任务列表查询");
    try{
        unordered_map<string, vector<TaskSingle>> all_map_tasks;
        all_map_tasks = __task_db_ptr->GetAllTaskSingleList();
        for(auto& kv : all_map_tasks){
            string map_name = kv.first;
            // 追加任务列表
            task_singles.insert(task_singles.end(), kv.second.begin(), kv.second.end());
        }
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }  
    return status;
}


/*******************************************
 * 组合任务管理
 * 注意：数据库中任务列表仅存储任务名称和地图名称，其它信息为默认值。
 * 查询组合任务时，需要补充单个任务相关信息。
 *******************************************/

// 组合任务添加
Status TaskManagerNode::TaskGroupAdd(TaskGroup& task_group){
    Status status;
    LogPub("INFO", "组合任务添加, group_name=" + task_group.group_name);
    try{
        if(task_group.group_name.empty())
            throw(string("group_name is empty."));
        // 检测是否已存在
        if(__task_db_ptr->CheckTaskGroupExist(task_group.group_name)){
            throw(string("group_name=" + task_group.group_name + "已存在。"));
        }
        // 执行添加操作
        __task_db_ptr->InsertTaskGroup(task_group);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }  
    return status;
}

// 组合任务删除
Status TaskManagerNode::TaskGroupDelete(string group_name){
    Status status;
    LogPub("INFO", "组合任务删除, group_name=" + group_name);
    try{
        if(group_name.empty())
            throw(string("group_name is empty."));
        __task_db_ptr->DeleteTaskGroup(group_name);

        // 更新定时任务下所有组合任务
        UpdateTimerTaskTaskGroupList(group_name, "", true);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }     
    return status;
}

// 删除所有组合任务
Status TaskManagerNode::TaskGroupDeleteAll(){
    Status status;
    LogPub("INFO", "删除所有组合任务");
    try{
        __task_db_ptr->DeleteAllTaskGroup();
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 组合任务更新名称
Status TaskManagerNode::TaskGroupRename(string task_group_name, string new_task_group_name){
    Status status;
    LogPub("INFO", "组合任务更新名称, group_name=" + task_group_name + ", new_task_group_name=" + new_task_group_name);
    try{
        // 检测是否已存在
        if(task_group_name.empty())
            throw(string("group_name is empty."));
        if(new_task_group_name.empty())
            throw(string("new group_name is empty."));
        if(__task_db_ptr->CheckTaskGroupExist(new_task_group_name)){
            throw(string("new group_name=" + new_task_group_name + "已存在。"));
        }
        __task_db_ptr->RenameTaskGroup(task_group_name, new_task_group_name);

        // 更新定时任务下所有组合任务
        UpdateTimerTaskTaskGroupList(task_group_name, new_task_group_name, false);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 设置置顶属性
Status TaskManagerNode::TaskGroupSetTop(string task_group_name, bool is_top){
    Status status;
    LogPub("INFO", "组合任务置顶属性设置, group_name=" + task_group_name
        + ", is_top=" + __msg_convert.Bool2Str(is_top));
    try{
        if(!__task_db_ptr->CheckTaskGroupExist(task_group_name)){
            throw(string("group_name=" + task_group_name + "不存在。"));
        }
        __task_db_ptr->UpdateTaskGroupIsTop(task_group_name, is_top);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 组合任务路径更新
Status TaskManagerNode::TaskGroupUpdatePath(string task_group_name){
    Status status;
    // 待补全
    return status;
}

// 补全组合任务全部信息，更新单个任务信息
void TaskManagerNode::TaskGroupComplete(TaskGroup& task_group){
    for(auto& task_single : task_group.task_list){
        string map_name = task_single.task_base.map_base.name;
        string task_name = task_single.task_base.task_name;
        try{
            // 补全单个任务所有信息
            __task_db_ptr->GetTaskSingle(map_name, task_name, task_single);
        }
        catch(string& error){
            LogPub("ERROR", "组合任务信息补全失败, map_name=" + map_name  +
                + ", task_name=" + task_name + ", error=" + error);
        }
        catch (exception &e){
            LogPub("ERROR", "组合任务信息补全失败, map_name=" + map_name  +
                + ", task_name=" + task_name + ", error=" + e.what());
        }
    }
}

// 组合任务信息查询
Status TaskManagerNode::TaskGroupQuery(string task_group_name, TaskGroup& task_group){
    Status status;
    LogPub("INFO", "组合任务信息查询, group_name=" + task_group_name);
    try{
        if(!__task_db_ptr->CheckTaskGroupExist(task_group_name)){
            throw(string("group_name=" + task_group_name + "不存在。"));
        }
        __task_db_ptr->GetTaskGroup(task_group_name, task_group);
        TaskGroupComplete(task_group);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 组合任务列表查询
Status TaskManagerNode::TaskGroupList(vector<TaskGroup>& task_groups){
    Status status;
    LogPub("INFO", "组合任务列表查询");
    try{
        task_groups = __task_db_ptr->GetTaskGroupList();
        for(auto& task_group : task_groups){
            TaskGroupComplete(task_group);
        }
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 更新所有组合任务下任务列表信息，用于单个任务重命名或删除操作
// is_delete true 删除，false 更新
void TaskManagerNode::TaskGroupUpdateTaskList(string map_name, string old_name, string new_name, bool is_delete){
    // 更新任务列表信息
    auto UpdateTaskList = [](vector<TaskSingle> task_list, string map_name, string old_name, string new_name, bool is_delete) -> vector<TaskSingle>
    {
        vector<TaskSingle> new_task_list;
        for(auto& task_single : task_list){
            if(task_single.task_base.task_name == old_name && task_single.task_base.map_base.name == map_name){
                if(is_delete) continue;
                task_single.task_base.task_name = new_name;
            }
            new_task_list.emplace_back(task_single);
        }
        return new_task_list;
    };

    vector<TaskGroup> task_groups = __task_db_ptr->GetTaskGroupList();
    for(auto &task_group : task_groups){
        task_group.task_list = UpdateTaskList(task_group.task_list, map_name, old_name, new_name, is_delete);
        if(task_group.task_list.empty()){
            // 如果任务组为空，删除此组合任务
            __task_db_ptr->DeleteTaskGroup(task_group.group_name);
        }
        else{
            __task_db_ptr->UpdateTaskGroupTaskList(task_group);
        }
    }
}

// 更新组合任务下任务列表地图名称，用于地图删除/重命名操作
// is_delete true 删除，false 更新
void TaskManagerNode::TaskGroupUpdateMapName(string map_name, string new_map_name, bool is_delete){
    // 更新地图名称
    auto UpdateMapName = [](vector<TaskSingle> task_list, string map_name, string new_map_name, bool is_delete) -> vector<TaskSingle>
    {
        vector<TaskSingle> new_task_list;
        for(auto& task_single : task_list){
            if(task_single.task_base.map_base.name == map_name){
                if(is_delete) continue;
                task_single.task_base.map_base.name = new_map_name;
            }
            new_task_list.emplace_back(task_single);
        }  
        return new_task_list;      
    };

    vector<TaskGroup> task_groups = __task_db_ptr->GetTaskGroupList();
    for(auto &task_group : task_groups){
        task_group.task_list = UpdateMapName(task_group.task_list, map_name, new_map_name, is_delete);
        if(task_group.task_list.empty()){
            // 如果任务组为空，删除此组合任务
            __task_db_ptr->DeleteTaskGroup(task_group.group_name);
        }
        else{
            __task_db_ptr->UpdateTaskGroupTaskList(task_group);
        }
    }   
}



/*******************************************
 * 定时任务管理
 * 注意：定时任务内组合任务仅包含组合任务名称，其余组合任务具体信息为默认值。
 *******************************************/
// 定时任务添加
Status TaskManagerNode::TimerTaskAdd(TimerTask& timer_task){
    Status status;
    LogPub("INFO", "定时任务添加, timertask_name=" + timer_task.timertask_name
        + ", data : " + __msg_convert.TimerTask2Str(timer_task));
    try{
        if(timer_task.timertask_name.empty())
            throw(string("timertask_name is empty."));
        if(timer_task.timetable.size() != 7){
            throw(string("please check timetable."));
        }
        // 检测是否已存在
        if(__task_db_ptr->CheckTimerTaskExist(timer_task.timertask_name)){
            throw(string("timertask_name=" + timer_task.timertask_name + "已存在。"));
        }
        __task_db_ptr->InsertTimerTask(timer_task);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 定时任务删除
Status TaskManagerNode::TimerTaskDelete(string timer_task_name){
    Status status;
    LogPub("INFO", "定时任务删除, timertask_name=" + timer_task_name);
    try{
        if(timer_task_name.empty())
            throw(string("timertask_name is empty."));
        if(!__task_db_ptr->CheckTimerTaskExist(timer_task_name)){
            throw(string("timertask_name=" + timer_task_name + "is not exist."));
        }
        __task_db_ptr->DeleteTimerTask(timer_task_name);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 删除指定地图下定时任务
Status TaskManagerNode::TimerTaskDeleteByMapName(string map_name){
    Status status;
    LogPub("INFO", "删除指定地图下所有定时任务，map_name is " + map_name);
    try{
        __task_db_ptr->DeleteTimerTaskByMapName(map_name);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 重命名地图，同步定时任务操作
Status TaskManagerNode::TimerTaskUpdateMapName(string map_name, string new_map_name){
    Status status;
    LogPub("INFO", "重命名地图，同步定时任务操作。map_name is " + map_name
        + ", new_map_name is " + new_map_name);
    try{
        __task_db_ptr->UpdateTimerTaskMapName(map_name, new_map_name);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 删除所有定时任务
Status TaskManagerNode::TimerTaskDeleteAll(){
    Status status;
    LogPub("INFO", "删除所有定时任务");
    try{
        __task_db_ptr->DeleteAllTimerTask();
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 定时任务数据整体更新
Status TaskManagerNode::TimerTaskUpdate(TimerTask& timer_task, TimerTask& new_timer_task){
    Status status;
    LogPub("INFO", "定时任务数据整体更新, timertask_name=" + timer_task.timertask_name
        + ", new_timer_task data : " + __msg_convert.TimerTask2Str(new_timer_task));
    try{
        // 新增时刻表尺寸检测
        if(new_timer_task.timetable.size() != 7){
            throw(string("please check timetable."));
        }
        // 重命名时，检测新定时任务数据是否已存在
        if(!new_timer_task.timertask_name.empty()
            && timer_task.timertask_name != new_timer_task.timertask_name){
            if(__task_db_ptr->CheckTimerTaskExist(new_timer_task.timertask_name)){
                throw(string(new_timer_task.timertask_name + "已存在."));
            }
        }
        __task_db_ptr->UpdateTimerTask(timer_task.timertask_name, new_timer_task);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 设置置顶属性
Status TaskManagerNode::TimerTaskSetTop(string timer_task_name, bool is_top){
    Status status;
    LogPub("INFO", "定时任务置顶属性设置, timertask_name=" + timer_task_name
        + ", is_top=" + __msg_convert.Bool2Str(is_top));
    try{
        if(!__task_db_ptr->CheckTimerTaskExist(timer_task_name)){
            throw(string("timertask_name=" + timer_task_name + "is not exist."));
        }
        __task_db_ptr->UpdateTimerTaskIsTop(timer_task_name, is_top);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 定时任务信息查询
Status TaskManagerNode::TimerTaskQuery(string timer_task_name, TimerTask& timer_task){
    Status status;
    LogPub("INFO", "定时任务信息查询, timertask_name=" + timer_task_name);
    try{
        if(timer_task_name.empty())
            throw(string("timertask_name is empty."));
        if(!__task_db_ptr->CheckTimerTaskExist(timer_task_name)){
            throw(string("timertask_name=" + timer_task_name + "is not exist."));
        }
        __task_db_ptr->GetTimerTask(timer_task_name, timer_task);
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}

// 定时任务列表查询
Status TaskManagerNode::TimerTaskList(vector<TimerTask>& timer_tasks){
    Status status;
    // LogPub("INFO", "定时任务列表查询");
    try{
        vector<TimerTask> timer_tasks_list = __task_db_ptr->GetTimerTaskList();
        for(auto& timer_task : timer_tasks_list){
            // 校验地图数据
            if(__map_name.empty()) continue;
            if(!timer_task.multi_maps_shared && timer_task.map_name != __map_name) continue;    //地图名称检测
            timer_tasks.emplace_back(timer_task);
        }
    }
    catch(string& error){
        status.success = false;
        status.message = error;
    }
    return status;
}


// 更新定时任务下所有组合任务，用于组合任务删除或重命名操作
// is_delete true 删除，false 更新
void TaskManagerNode::UpdateTimerTaskTaskGroupList(string old_name, string new_name, bool is_delete){
    // 更新组合任务列表
    auto taskgroup_list = [](vector<TaskGroup> taskgroup_list, string& old_name, string& new_name, bool is_delete) -> vector<TaskGroup> 
    {
        vector<TaskGroup> new_taskgroup_list;
        for(auto& taskgroup : taskgroup_list){
            if(taskgroup.group_name == old_name){
                if(is_delete) continue;
                taskgroup.group_name = new_name;
            }
            new_taskgroup_list.emplace_back(taskgroup);      
        }
        return new_taskgroup_list;
    };

    vector<TimerTask> timer_tasks = __task_db_ptr->GetTimerTaskList();
    for(auto& timer_task : timer_tasks){
        timer_task.taskgroup_list = taskgroup_list(timer_task.taskgroup_list, old_name, new_name, is_delete);
        __task_db_ptr->UpdateTimerTaskGroupList(timer_task);
    }

}

// // 同步更新数据库内容
// void SyncDataBase(){
//     // 获取地图名称列表
//     unordered_map<string> map_name_list;
//     if(__map_list_ptr){
//         for(auto map_base : __map_list_ptr->list){
//             map_name_list.insert(map_base.name);
//         }  
//     }
//     // 检查定时任务数据




// }

// 获取地图列表
vector<string> TaskManagerNode::GetMapList(){
    vector<string> map_list;
    map_list = file_manager::ListDirWithDepth1(__maps_dir, 1);
    return map_list;
}


// 兼容数据并备份数据库文件
void TaskManagerNode::TaskDataCompatible(string cache_dir){
    // 数据库备份目录
    string backup_dir = cache_dir + "db_backup/";
    file_manager::CreateDir(backup_dir);

    __task_db_ptr->DeleteNullData();

    vector<string> map_list = GetMapList();
    cout << "get map list: " << endl;
    for(auto map_name : map_list){
        cout << "--> map_name: " << map_name << endl;
    }

    // 是否在地图中
    auto InMaplist = [&](vector<string>& map_list, string map_name) -> bool {
        for(auto map_item : map_list){
            if(map_name == map_item) return true;
        }
        return false;
    };

    // 备份任务数据
    vector<TaskSingle> task_list = __data_compatible.AllTaskData();
    for(auto& task_single : task_list){
        // 如果在数据库中不存在
        string map_name = task_single.task_base.map_base.name;
        string task_name = task_single.task_base.task_name;
        if(!InMaplist(map_list, map_name)){
            LogPub("WARN", "地图不存在，跳过, task_name=" + task_name + ", map_name=" + map_name);
            continue;
        }
        if(__task_db_ptr->CheckTaskSingleExist(map_name, task_name)){
            LogPub("INFO", "任务已存在, task_name=" + task_name + ", map_name=" + map_name);
            continue;
        }
        __task_db_ptr->InsertTaskSingle(task_single);
        LogPub("INFO", "兼容适配，插入任务 task_name=" + task_name + ", map_name=" + map_name);

        // 同步更新组合任务一份
        TaskGroup task_group;
        task_group.group_name = task_name;
        task_group.task_list.emplace_back(task_single);
        __task_db_ptr->InsertTaskGroup(task_group);
        LogPub("INFO", "兼容适配，插入组合任务 group_name=" + task_group.group_name);
    }

    // 备份定时任务数据
    vector<TimerTask> timer_task_list = __data_compatible.AllTimerTaskData();
    vector<TimerTask> elevator_timer_task_list = __data_compatible.AllElevatorTimerTaskData();
    timer_task_list.insert(timer_task_list.end(), elevator_timer_task_list.begin(), elevator_timer_task_list.end());
    for(auto timer_task : timer_task_list){
        string timer_task_name = timer_task.timertask_name;
        string map_name = timer_task.map_name;
        bool multi_maps_shared = timer_task.multi_maps_shared;
        if(!multi_maps_shared && !InMaplist(map_list, map_name)){
            LogPub("WARN", "地图不存在，跳过, timer_task_name=" + timer_task_name + ", map_name=" + map_name);
            continue;
        }
        // 检测是否已存在
        if(__task_db_ptr->CheckTimerTaskExist(timer_task_name)){
            LogPub("INFO", "定时任务已存在, timer_task_name=" + timer_task_name);
        }
        __task_db_ptr->InsertTimerTask(timer_task);
        LogPub("INFO", "兼容适配，插入定时任务, timer_task_name=" + timer_task_name);
    }

    // 备份任务记录数据
    vector<TaskRecord> task_record_list = __data_compatible.AllTaskRecordData();
    for(auto task_record : task_record_list){
        LogPub("INFO", "兼容适配，插入任务记录, group_name=" + task_record.task_group.group_name
            + ", group_id=" + task_record.task_group.group_id
            + ", add_time=" + task_record.add_time
            );
        // 插入到数据库
        __task_db_ptr->InsertTaskRecordWithSaveTime(task_record, task_record.add_time);
    }

    // 备份至目录文件
    file_manager::MoveFileToDir(__data_compatible.GetTaskDB(), backup_dir);
    file_manager::MoveFileToDir(__data_compatible.GetElevatorTimerTaskDB(), backup_dir);
    file_manager::MoveFileToDir(__data_compatible.GetTaskRecordDB(), backup_dir);
}
